#!/bin/bash
#
# USAGE:
#       quejob adore_command [outputFolder] -- [qsub options]
#
# DESCRIPTION:
#  quejob is an internal ADORE command.  
#  It runs the given adore command in the Torque-PBS system.
#  Quejob uses the Torque-PBS system to distribute jobs to other computers.
#
# INPUT:
#	adore_command: commands to submit to the PBS. If multiple commands are used, this should be a string in quotations. See examples.
#
#   OPTIONAL:	
#	outputFolder: specify output folder for the ADORE command. Default is current folder ("$PWD").
#  
# OUTPUT:
#  Creates ${tmpFolder}/{randomFile}.set and  ${tmpFolder}/{randomFile}.sh 
#

function createJob(){
local qsubPath=`which qsub`
[ "${qsubPath:-IsEmpty}" == "IsEmpty" ] && echo "Torque PBS, qsub, not found." >&2 && return 110

local commands=${1};
local CALLDIR qsubOpts jobId
if [ "${2:-isEmpty}" == "isEmpty" ]; then
  CALLDIR="${PWD}";
  qsubOpts=""
elif [ -d "${2}" ]; then 
  CALLDIR="${2}"
  qsubOpts="${@:4}"
elif [ "${2}" == "--" ]; then 
  CALLDIR="${PWD}";  
  qsubOpts="${@:3}"
else
  echo "Wrong parameter. Please check usage with: ? quejob" >&2 && return 110
fi

#if options are not specified using commandline check any environment options. 
[ -z ${qsubOpts} ] && qsubOpts="${parallel_options}"

generateRandomString 
local queJobRandStr=${randomString}
mkdir -p ${tmpFolder} 
local originalSettingsFile=${tmpFolder}/${queJobRandStr}.set
settings save ${originalSettingsFile} 1>> ${tmpFolder}/${queJobRandStr}.log #Do not dump messages

cat >${tmpFolder}/${queJobRandStr}.sh<<_EOFFILE
#!/bin/bash
 #PBS -N parallelJob
 #PBS -l nodes=1
 #PBS -V
 #PBS -l walltime=8:00:00
 #PBS -m n
 #PBS -e ${CALLDIR}/${queJobRandStr}.err
 #PBS -o ${CALLDIR}/${queJobRandStr}.out
 
 cd ${CALLDIR}
 ${ADORESCR}/adore -u "${tmpFolder}/${queJobRandStr}.set" "${commands}"
_EOFFILE
 #PBS -q batch # No need to specify quename. We send it to default que. 
 #PATH is exported to prevent errors in case -V makes a mistake.
 
#submit the job to the que
jobId=`qsub ${qsubOpts} "${tmpFolder}/${queJobRandStr}.sh"`
echo "${jobId}@${HOSTNAME}"
}

createJob "${@}"
